package pl.uz.zgora.plan;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class PersDatabaseHandler extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "PERS";
	private static final String DB_PATH = "/data/data/pl.uz.zgora.plan/databases/";
	public static final String KEY_NAUCZYCIEL = "idNauczyciela";
	public static final String TABLE_NAUCZYCIEL_PERS = "NauczycielPers";
	public static final String KEY_NAME = "nazwa";
	private static Context mContext = null;
	private SQLiteDatabase mDataBase;

	private static final String CREATE_NAUCZYCIEL_PERS_TABLE = "create table "
			+ TABLE_NAUCZYCIEL_PERS + "( " + KEY_NAUCZYCIEL
			+ " integer primary key, " + KEY_NAME + " text not null);";

	private static final String DROP_NAUCZYCIEL_PERS_TABLE = "DROP TABLE IF EXISTS "
			+ TABLE_NAUCZYCIEL_PERS + ";";

	public PersDatabaseHandler(Context context) throws IOException {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		PersDatabaseHandler.mContext = context;
		mDataBase = getReadableDatabase();
		createDataBase();
	}
	/**
	 * Usuwa dane z tabeli i tworzy nową pustą tabele
	 * Funkcja jest wykorzystywana podczas aktualizacji bazy zawierajacej ID wykładowców w systemie PERS
	 * @param context
	 * @param removeDB
	 * true - usunięcie tabeli i utworzenie nowej, pustej tabeli
	 */
	public PersDatabaseHandler(Context context, boolean removeDB) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		PersDatabaseHandler.mContext = context;
		mDataBase = getWritableDatabase();
		init(mDataBase, removeDB);
	}

	public SQLiteDatabase openDataBase() throws SQLException {

		// Open the database
		final String dbPath = DB_PATH + DATABASE_NAME;
		mDataBase = SQLiteDatabase.openDatabase(dbPath, null,
				SQLiteDatabase.OPEN_READONLY);
		
		return mDataBase;

	}

	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
		} else {
			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			this.getReadableDatabase();

			try {
				copyDataBase();
			} catch (IOException e) {
				throw new Error("Error copying database: " + e.getLocalizedMessage());
			}
		}
	}
	
	/**
	 * Sprawdza czy istnieje baza danych zawierająca identyfikatory wszystkich
	 * pracowników (w systemie PERS), oraz czy posiada ona poprawną strukturę.
	 * Funkcja sprawdza również, czy tabele posiadaja dane.
	 * 
	 * @return Stan bazy danych<br/>
	 *         <b>true</b> - baza danych ma poprawną strukturę i zawiera dane<br/>
	 *         <b>false</b> - baza danych jest nieprawidłowa
	 */
	private boolean checkDataBase() {
		final String dbPath = DB_PATH + DATABASE_NAME;
		final SQLiteDatabase checkDB = SQLiteDatabase.openDatabase(dbPath,
				null, SQLiteDatabase.OPEN_READONLY);
		
		if(checkDB != null){
			Cursor cursor = null;
			try {
			cursor = mDataBase.query(PersDatabaseHandler.TABLE_NAUCZYCIEL_PERS,
					null, "nazwa LIKE '%a%'", null, null, null, null);
			cursor.moveToFirst();
			if(cursor.getCount() == 0) { cursor.close(); checkDB.close(); return false; }
			} catch (SQLException e) {
				if(cursor != null) { cursor.close(); }
				
				checkDB.close();
				return false;
			}
			cursor.close(); 
			checkDB.close();
		}

		return checkDB != null ? true : false;
	}

	private void init(SQLiteDatabase db, boolean removeDB) {
		if(removeDB) {
			db.execSQL(DROP_NAUCZYCIEL_PERS_TABLE);
		}
		db.execSQL(CREATE_NAUCZYCIEL_PERS_TABLE);
	}
	
	 private void copyDataBase() throws IOException{
		 InputStream myInput = mContext.getAssets().open(DATABASE_NAME);
		 String outFileName = DB_PATH + DATABASE_NAME;
		 OutputStream myOutput = new FileOutputStream(outFileName);

		 byte[] buffer = new byte[1024];
		 int length = 0;
		 while ((length = myInput.read(buffer))>0){
			 myOutput.write(buffer, 0, length);
		 }

		 //Close the streams
		 myOutput.flush();
		 myOutput.close();
		 myInput.close();
	 }

	@Override
	public void onCreate(SQLiteDatabase db) {}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
	
	public synchronized void close() {
		 
	    if(mDataBase != null)
	    	mDataBase.close();

	    super.close();
	}
}
